package com.android.lj.app.net;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class NetSpeedConfigActivity extends Activity {

	public static int MESSAGE_TYPE_ERROR = -1;
	public static int MESSAGE_TYPE_MESSAGE = 0;
	public static int MESSAGE_TYPE_STOP_COMMAND = 1;
	public static int MESSAGE_TYPE_START_COMMAND = 2;
	
	private Thread monitorThread;
	private Handler handler;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);

        handler = new Handler(){
        	@Override
	        public void handleMessage(Message msg) {
	        	if(NetSpeedConfigActivity.MESSAGE_TYPE_MESSAGE == msg.what) {
	        		String message = (String) msg.obj;
	        		TextView speedText = (TextView) findViewById(R.id.inSpeedValue);
	        		speedText.setText(message);
	        	}
	        }
        };
        addBtnStartListeners(this);
        addBtnStopListeners(this);
        
        
    }
    
    private void addBtnStartListeners(final NetSpeedConfigActivity activity) {
		Button btnStart = (Button) findViewById(R.id.btnStart);
		btnStart.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				activity.monitorThread = new SpeedThread(handler);
				activity.monitorThread.start();
			}});
	}
    
    private void addBtnStopListeners(final NetSpeedConfigActivity activity) {
		Button btnStop = (Button) findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				activity.monitorThread.stop();
				activity.finish();
			}});
	}

	private class SpeedThread extends Thread {
		private Handler handler = null;
		private Activity activity = null;
		public SpeedThread(Handler handler, Activity activity) {
			this.handler = handler;
			this.activity = activity;
		}
    	@Override
    	public void run() {
    		try {
	    		while (true) {
	    			Message msg = new Message();
	    			msg.what = NetSpeedConfigActivity.MESSAGE_TYPE_MESSAGE;
	    			msg.obj = NetSpeedUtil.getInSpeed(activity);
					handler.sendMessage(msg);
		            sleep(1000);
	    		}
    		}catch (Exception e) {
    			Message msg = new Message();
    			msg.what = NetSpeedConfigActivity.MESSAGE_TYPE_ERROR;
    			msg.obj = e.getMessage();
				handler.sendMessage(msg);
    		}
    	}
    }
}